package com.tc.mongo;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import com.tc.mongo.service.MongodbService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
public class MongodbServiceImpl implements MongodbService {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(MongodbService.class);

    /**
     * mongoDB数据库连接
     */
    private DB db;

    /**
     * 文件操作句柄
     */
    private GridFS gridFS;

    /**
     * 线程锁
     */
    private final String mongoDBLock = "mongoDB";

    @Autowired
    private MongoTemplate mongoTemplate;

//    @Autowired
//    private LoggerInfoService loggerInfoService;


    @Override
    public boolean isExist(String fileName, boolean includePostfix) throws Exception {

        if (fileName == null || fileName.trim().equals("")) {
            throw new IllegalArgumentException("fileName(" + fileName + ")格式不正确");
        }
        GridFSDBFile gridFSDBFile;
        try {
            logger.info("配置mongoDB数据库before");
            initConfig();
            logger.info("配置mongoDB数据库after");
            if (includePostfix)
                gridFSDBFile = gridFS.findOne(new BasicDBObject("filename", fileName));
            else
                gridFSDBFile = gridFS.findOne(new BasicDBObject("_id", fileName));
        } catch (Exception e) {
            logger.info("服务器异常,异常信息为:" + CommonUtil.getTextFromException(e));
//            loggerInfoService.addLoggerInfo(new LoggerInfo(CommonUtil.getUuid(), LoggerInfoService.BAFS_API, this.getClass().getName(), "isExist", CommonUtil.getTextFromException(e)));
            throw new Exception("服务器异常,异常信息为:" + CommonUtil.getTextFromException(e));
        }
        return gridFSDBFile != null;
    }

    @Override
    public boolean createAttachment(byte[] bytes, String fileName, String fileType) {

        if (bytes == null || bytes.length == 0) {
            throw new IllegalArgumentException("bytes不能为空");
        }

        if (fileName == null || fileName.trim().equals("")) {
            throw new IllegalArgumentException("fileName(" + fileName + ")格式不正确");
        }

        if (fileType == null || fileType.trim().equals("")) {
            throw new IllegalArgumentException("fileType(" + fileType + ")格式不正确");
        }

        boolean isSuccess = false;
        try {
            logger.info("配置mongoDB数据库before");
            initConfig();
            logger.info("配置mongoDB数据库after");
            GridFSInputFile gridFSInputFile = gridFS.createFile(bytes);
            fileName = new StringBuilder(fileName).append(".").append(fileType).toString();
            gridFSInputFile.put("_id", fileName);
            gridFSInputFile.put("filename", fileName);
            gridFSInputFile.put("contentType", fileType);
            gridFSInputFile.save();
            isSuccess = true;
        } catch (Exception e) {
            logger.info("服务器异常,异常信息为:" + CommonUtil.getTextFromException(e));
//            loggerInfoService.addLoggerInfo(new LoggerInfo(CommonUtil.getUuid(), LoggerInfoService.BAFS_API, this.getClass().getName(), "createAttachment", CommonUtil.getTextFromException(e)));
        }
        return isSuccess;
    }

    @Override
    public InputStream getImageInputStream(String fileName, boolean includePostfix) throws Exception {

        if (fileName == null || fileName.trim().equals("")) {
            throw new IllegalArgumentException("fileName(" + fileName + ")格式不正确");
        }

        InputStream inputStream;
        try {
            logger.info("配置mongoDB数据库before");
            initConfig();
            logger.info("配置mongoDB数据库after");
            GridFSDBFile gridFSDBFile;
            if (includePostfix)
                gridFSDBFile = gridFS.findOne(new BasicDBObject("filename", fileName));
            else
                gridFSDBFile = gridFS.findOne(new BasicDBObject("_id", fileName));
            if (gridFSDBFile != null) {
                logger.info("生成图片字节流");
                inputStream = gridFSDBFile.getInputStream();
                logger.info("图片字节流生成完成");
            } else {
                logger.info("图片字节流生成失败");
                throw new Exception("当前附件(" + fileName + ")不存在");
            }
        } catch (Exception e) {
            logger.info("服务器异常,异常信息为:" + CommonUtil.getTextFromException(e));
//            loggerInfoService.addLoggerInfo(new LoggerInfo(CommonUtil.getUuid(), LoggerInfoService.BAFS_API, this.getClass().getName(), "getImageInputStream", CommonUtil.getTextFromException(e)));
            throw new Exception("服务器异常,异常信息为:" + CommonUtil.getTextFromException(e));
        }
        return inputStream;
    }

    /**
     * 初始化配置
     */
    private void initConfig() {
        if (db == null || gridFS == null) {
            synchronized (mongoDBLock) {
                if (db == null || gridFS == null) {
                    db = mongoTemplate.getDb();
                    gridFS = new GridFS(db, "fs");
                }
            }
        }

    }
}
